package com.general.template.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.general.template.config.UploadProperties;
import com.general.template.utils.IdWorker;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.*;

/**
 * @Author: 杰哥
 * @Description:
 **/
@Component
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {
    private Log log= LogFactory.getLog(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private IdWorker worker;

    @Autowired
    private UploadProperties prop;

    public String uploadImage(MultipartFile file) {
        // 1、校验文件类型
//        String contentType = file.getContentType();
//        if (!prop.getAllowTypes().contains(contentType)) {
//            throw new RuntimeException("文件类型不支持");
//        }
        // 2、校验文件内容
//        try {
//            BufferedImage image = ImageIO.read(file.getInputStream());
//            if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
//                throw new RuntimeException("上传文件有问题");
//            }
//        } catch (IOException e) {
//            log.error("校验文件内容失败....{}", e);
//            throw new RuntimeException("校验文件内容失败"+e.getMessage());
//        }

        try {
            // 3、上传到FastDFS
            // 3.1、获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 3.2、上传
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 返回路径
            return prop.getBaseUrl() + storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败！....{}", e);
            throw  new RuntimeException("【文件上传】上传文件失败！"+e.getMessage());
        }
    }

    public String uploadAdmin(MultipartFile file){
        String suffix = null;
        try {
            suffix = file.getOriginalFilename().split("\\.")[1];
        }catch (Exception e){
            return null;
        }
        String id = Long.valueOf(worker.nextId()).toString();
        String filename =id+"."+suffix;
        try {
            InputStream inputStream = file.getInputStream();
            Files.copy(inputStream,new File(prop.getUploadAdmin()+filename).toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop.getBaseAdmin()+filename;
    }

    public Map<String,Object> uploadMedia(MultipartFile[] file){
        Map<String,Object> map = new HashMap<>(16);
        List<String> name = new ArrayList<>();
        List<String> url = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            String suffix = null;
            String[] split = null;
            try {
                split = Objects.requireNonNull(multipartFile.getOriginalFilename()).split("\\.");
                suffix = split[1];
            } catch (Exception e) {
                return null;
            }
            String id = Long.valueOf(worker.nextId()).toString();
            String filename = split[0] + "_" + id + "." + suffix;
            try {
                InputStream inputStream = multipartFile.getInputStream();
                Files.copy(inputStream, new File(prop.getUploadMedia() + filename).toPath());
                name.add(multipartFile.getOriginalFilename());
                url.add(prop.getBaseMedia() + filename);
            } catch (IOException e) {
                e.printStackTrace();
            }
            map.put("name", JSON.toJSONString(name));
            map.put("url", JSON.toJSONString(url));
        }
        return map;
    }
}

